{% extends 'layout/header.html' %}

{% block body %}
    <div style="width: 500px;margin: 200px auto;">
        <form id="f1" action="/login/" method="POST" novalidate>
            {% csrf_token %}
            {% for field in form %}
                <div class="form-group">
                    <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                    <div class="row">
                        <div class="col-xs-7">
                            {{ field }}
                            <span class="error-msg">{{ field.errors.0 }}</span>
                        </div>
                    </div>
                </div>
            {% endfor %}
            <input type="submit" class="btn btn-default" value="登 录"/>
            <a onclick="submitForm();">登 录</a>
        </form>

    </div>
{% endblock %}

{% block js %}
    <script>

    function submitForm() {
        $('.error-msg').empty()
        $.ajax({
            url: '/ajax_login/',
            type: 'POST',
            data: $('#f1').serialize(),// user=alex&pwd=456&csrftoen=xxx\
            dataType: "JSON",
            success: function (arg) {
                console.log(arg)
                if (arg.status) {
                    location.href = arg.data;
                } else {
                    $.each(arg.error, function (key,value) {
                        $("#id_" + key).next().text(value[0]);
                    })
                }
            }
        })
    }

    </script>
{% endblock %}